<?php
/**
 * Author: zsw zswemail@qq.com
 */

namespace app\backend\logic;


use app\backend\model\Attachment as AttachmentModel;

class Attachment
{

    public static function tableList($where = [], $order = '', $page = 1, $row_num = 15)
    {
        $field = 'id, uploader, uuid ,name,url,ip,size,mime,width,height,suffix, create_time, domain';
        $model = (new AttachmentModel())->field($field)->where($where);
        $count = $model->count();
        $list = $model->order($order ?: 'id DESC')->page($page, $row_num)->select()->toArray();
        foreach ($list as &$v) {
            $v['url'] = $v['domain'] . $v['url'];
            $v['wh'] = $v['width'] . '×' . $v['height'];
            if ($v['size'] > 1000000) {
                $v['size_label'] = number_format($v['size'] / 1000000,0,","," ") . ' MB';
            }elseif ($v['size'] > 1000) {
                $v['size_label'] = number_format($v['size'] / 1000,0,","," ") . ' KB';
            }else{
                $v['size_label'] = $v['size'] . ' B';
            }
            $v['uploader_name'] = \app\backend\model\Admin::where('id', $v['uploader'])->value('username', '');
        }
        return [
            'count' => $count,
            'list' => $list
        ];
    }

    public static function delete($id)
    {
        $urls = AttachmentModel::where(['id' => $id])->column('url', 'id');
        if ($urls && AttachmentModel::destroy($id)) {
            foreach ($urls as $u) {
                // 删除文件
            }
        }
        return true;
    }


}
